#version 140
#extension GL_EXT_gpu_shader4 : enable 

uniform sampler2DArray TerrainTex;
uniform float TextureIndexes[32]; 

in vec2 TexCoord;
in vec3 Normal;
in vec4 TexValue1;
in vec4 TexValue2;
in vec4 TexValue3;
in vec4 TexValue4;

out vec4 FragColor;

void main()
{ 	
	FragColor = vec4(0.0, 0.0, 0.0, 1.0);
	
	// read the color
	for (int i=0; i<4; ++i)
	{
		if (TexValue1[i] > 0.0) FragColor.rgb += texture2DArray(TerrainTex, vec3(TexCoord,TextureIndexes[   i])).rgb * TexValue1[i];
		if (TexValue2[i] > 0.0) FragColor.rgb += texture2DArray(TerrainTex, vec3(TexCoord,TextureIndexes[ 4+i])).rgb * TexValue2[i];
		if (TexValue3[i] > 0.0) FragColor.rgb += texture2DArray(TerrainTex, vec3(TexCoord,TextureIndexes[ 8+i])).rgb * TexValue3[i];
		if (TexValue4[i] > 0.0) FragColor.rgb += texture2DArray(TerrainTex, vec3(TexCoord,TextureIndexes[12+i])).rgb * TexValue4[i];
	}
	
	// lighting
	vec3 n = normalize(Normal);
	vec3 lightDir = vec3(0,1,0);
	
	float ambient = 0.3;
	float diffuse = max(0.0, dot(n, lightDir ));
	FragColor = vec4(FragColor.rgb * (ambient + diffuse), 1.0);
}
